import { Provide} from '@midwayjs/core';
import { Pet } from '../../entity/user/pets';
import { Petpic } from '../../entity/user/petpic'
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';


@Provide()
export class PetService {

  @InjectEntityModel(Pet)
  petModel:Repository<Pet>


  async petinfo(id): Promise<Pet> {
    try {
      const result = await this.petModel.findOne({
        where: {
          id: id
        },
        relations: ['petpic']
      });
      return result;
    } catch (err) {
      console.log('err', err);
    }
  }
  
  async getpetinfo(ownerid: string):Promise<Pet[]>{
    try{
      const result = await this.petModel.find({
        where: {
          ownerid:ownerid
        },
        relations: ['petpic']
      })   
      return result
    }catch(err){
      console.log("err",err);
      
    }
  }
  
  async addpet(pet:Pet):Promise<Pet>{
    try{
      const result = await this.petModel.save(pet);
      console.log("result",result);
      return result
    }catch(err){
      console.log("err",err);
      
    }
  }

  async updatepet(pet:Pet):Promise<Pet>{
    try{
      const data = await this.petModel.findOne({
        where:{
            id:pet.id
        }
      })
      data.name=pet.name
      data.sex=pet.sex
      data.kindid=pet.kindid
      data.age=pet.age
      const result = await this.petModel.save(data);
      console.log("result",result);
      return result
    }catch(err){
      console.log("err",err);
      
    }
  }

  async deletepet(petid: string){
    try{
      const result = await this.petModel.delete(petid)   
      return result
    }catch(err){
      console.log("err",err);
      
    }
  }



  @InjectEntityModel(Petpic)
  PetpicModel:Repository<Petpic>

  async addpetpic(data:string,petid:string):Promise<Petpic>{
    try{
      let petpic = new Petpic();
      petpic.imageurl=data;
      petpic.petid=petid;
      const result = await this.PetpicModel.save(petpic);
      return result
    }catch(err){
      console.log("err",err);
      
    }
  }
  async updatepetpic(data:string,petid:string):Promise<Petpic>{
    try{
      const info = await this.PetpicModel.findOne({
        where:{
            petid:petid
        }
      })
      info.imageurl=data;
      const result = await this.PetpicModel.save(info);
      return result
    }catch(err){
      console.log("err",err);
      
    }
  }
  
}
